<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>阿里云语音识别测试</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #1890ff;
            text-align: center;
            margin-bottom: 30px;
        }
        .section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #e8e8e8;
            border-radius: 8px;
        }
        .section h3 {
            color: #333;
            margin-top: 0;
        }
        .config-group {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 20px;
        }
        .config-item {
            flex: 1;
            min-width: 200px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        select, input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            font-size: 14px;
        }
        .button-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        .btn-primary {
            background-color: #1890ff;
            color: white;
        }
        .btn-primary:hover {
            background-color: #40a9ff;
        }
        .btn-success {
            background-color: #52c41a;
            color: white;
        }
        .btn-success:hover {
            background-color: #73d13d;
        }
        .btn-danger {
            background-color: #ff4d4f;
            color: white;
        }
        .btn-danger:hover {
            background-color: #ff7875;
        }
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        .btn-secondary:hover {
            background-color: #868e96;
        }
        .status {
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
            font-weight: bold;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .status.connecting {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        .log-container {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 15px;
            height: 300px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        .log-entry {
            margin-bottom: 5px;
            padding: 2px 0;
        }
        .log-info {
            color: #1890ff;
        }
        .log-success {
            color: #52c41a;
        }
        .log-error {
            color: #ff4d4f;
        }
        .log-warning {
            color: #faad14;
        }
        .result-container {
            background-color: #f0f8ff;
            border: 1px solid #b3d9ff;
            border-radius: 4px;
            padding: 15px;
            min-height: 100px;
        }
        .result-text {
            font-size: 16px;
            line-height: 1.6;
            color: #333;
        }
        .metrics {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        .metric-item {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            text-align: center;
        }
        .metric-value {
            font-size: 24px;
            font-weight: bold;
            color: #1890ff;
        }
        .metric-label {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎤 阿里云语音识别测试</h1>
        
        <!-- 访问提示 -->
        <div class="section" style="background-color: #fff3cd; border-color: #ffeaa7;">
            <h3>⚠️ 访问提示</h3>
            <p><strong>推荐访问方式：</strong></p>
            <p>请通过HTTP服务器访问此页面，而不是直接打开HTML文件：</p>
            <p><code>http://localhost:7777/static-pages/aliyun_asr_test.html</code></p>
            <p><strong>原因：</strong>直接打开HTML文件会导致WebSocket连接失败，因为浏览器安全限制不允许file://协议建立WebSocket连接。</p>
        </div>
        
        <!-- 连接状态 -->
        <div class="section">
            <h3>连接状态</h3>
            <div id="status" class="status disconnected">未连接</div>
            <div class="button-group">
                <button id="connectBtn" class="btn-primary" onclick="connect()">连接</button>
                <button id="disconnectBtn" class="btn-secondary" onclick="disconnect()" disabled>断开</button>
            </div>
        </div>

        <!-- 配置选项 -->
        <div class="section">
            <h3>识别配置</h3>
            <div class="config-group">
                <div class="config-item">
                    <label for="model">模型选择:</label>
                    <select id="model">
                        <option value="paraformer-realtime-v2">paraformer-realtime-v2 (推荐)</option>
                        <option value="paraformer-realtime-8k-v2">paraformer-realtime-8k-v2 (8k)</option>
                        <option value="paraformer-realtime-v1">paraformer-realtime-v1</option>
                        <option value="paraformer-realtime-8k-v1">paraformer-realtime-8k-v1 (8k)</option>
                    </select>
                </div>
                <div class="config-item">
                    <label for="sampleRate">采样率:</label>
                    <select id="sampleRate">
                        <option value="16000">16kHz</option>
                        <option value="8000">8kHz</option>
                    </select>
                </div>
                <div class="config-item">
                    <label for="format">音频格式:</label>
                    <select id="format">
                        <option value="pcm">PCM</option>
                        <option value="wav">WAV</option>
                    </select>
                </div>
                <div class="config-item">
                    <label for="languageHints">语言提示:</label>
                    <input type="text" id="languageHints" value="zh,en" placeholder="zh,en">
                </div>
            </div>
        </div>

        <!-- 控制按钮 -->
        <div class="section">
            <h3>识别控制</h3>
            <div class="button-group">
                <button id="startBtn" class="btn-success" onclick="startRecognition()" disabled>开始识别</button>
                <button id="stopBtn" class="btn-danger" onclick="stopRecognition()" disabled>停止识别</button>
                <button id="clearBtn" class="btn-secondary" onclick="clearResults()">清空结果</button>
            </div>
        </div>

        <!-- 识别结果 -->
        <div class="section">
            <h3>识别结果</h3>
            <div id="resultContainer" class="result-container">
                <div class="result-text">等待开始识别...</div>
            </div>
        </div>

        <!-- 性能指标 -->
        <div class="section">
            <h3>性能指标</h3>
            <div class="metrics">
                <div class="metric-item">
                    <div id="requestId" class="metric-value">-</div>
                    <div class="metric-label">请求ID</div>
                </div>
                <div class="metric-item">
                    <div id="firstDelay" class="metric-value">-</div>
                    <div class="metric-label">首包延迟(ms)</div>
                </div>
                <div class="metric-item">
                    <div id="lastDelay" class="metric-value">-</div>
                    <div class="metric-label">末包延迟(ms)</div>
                </div>
                <div class="metric-item">
                    <div id="audioChunks" class="metric-value">0</div>
                    <div class="metric-label">音频包数量</div>
                </div>
            </div>
        </div>

        <!-- 日志 -->
        <div class="section">
            <h3>运行日志</h3>
            <div id="logContainer" class="log-container"></div>
        </div>
    </div>

    <script>
        // 阿里云ASR测试页面JavaScript逻辑
        let ws = null;
        let isConnected = false;
        let isRecognizing = false;
        let audioContext = null;
        let mediaStream = null;
        let audioChunks = 0;
        let clientId = null;

        // 获取WebSocket URL
        function getWebSocketUrl() {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            let hostname = window.location.hostname;
            let port = window.location.port;
            
            // 处理file://协议的情况
            if (window.location.protocol === 'file:') {
                hostname = 'localhost';
                port = '8000';
            }
            
            // 如果没有端口号，使用默认端口
            if (!port) {
                port = '8000';
            }
            
            const wsUrl = `${protocol}//${hostname}:${port}/ws/aliyun_asr_v2`;
            
            // 添加调试信息
            console.log('WebSocket URL构建信息:', {
                protocol: window.location.protocol,
                hostname: hostname,
                port: port,
                wsUrl: wsUrl
            });
            
            return wsUrl;
        }

        // 更新状态显示
        function updateStatus(status, message) {
            const statusEl = document.getElementById('status');
            statusEl.className = `status ${status}`;
            statusEl.textContent = message;
        }

        // 添加日志
        function addLog(message, type = 'info') {
            const logContainer = document.getElementById('logContainer');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry log-${type}`;
            logEntry.textContent = `[${timestamp}] ${message}`;
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        // 更新性能指标
        function updateMetrics(metrics) {
            if (metrics.request_id) {
                document.getElementById('requestId').textContent = metrics.request_id.substring(0, 8) + '...';
            }
            if (metrics.first_package_delay_ms !== undefined) {
                document.getElementById('firstDelay').textContent = metrics.first_package_delay_ms;
            }
            if (metrics.last_package_delay_ms !== undefined) {
                document.getElementById('lastDelay').textContent = metrics.last_package_delay_ms;
            }
        }

        // 连接WebSocket
        async function connect() {
            if (isConnected) return;

            try {
                updateStatus('connecting', '正在连接...');
                addLog('正在连接阿里云ASR服务...', 'info');

                const wsUrl = getWebSocketUrl();
                
                // 检查URL是否有效
                if (wsUrl.includes('ws://:') || wsUrl.includes('wss://:')) {
                    throw new Error('WebSocket URL无效，请通过HTTP服务器访问此页面');
                }

                ws = new WebSocket(wsUrl);
                
                ws.onopen = function() {
                    isConnected = true;
                    updateStatus('connected', '已连接');
                    addLog('WebSocket连接成功', 'success');
                    
                    document.getElementById('connectBtn').disabled = true;
                    document.getElementById('disconnectBtn').disabled = false;
                    document.getElementById('startBtn').disabled = false;
                };

                ws.onmessage = function(event) {
                    try {
                        const data = JSON.parse(event.data);
                        handleMessage(data);
                    } catch (e) {
                        addLog(`解析消息失败: ${e.message}`, 'error');
                    }
                };

                ws.onclose = function() {
                    isConnected = false;
                    updateStatus('disconnected', '连接已断开');
                    addLog('WebSocket连接已断开', 'warning');
                    
                    document.getElementById('connectBtn').disabled = false;
                    document.getElementById('disconnectBtn').disabled = true;
                    document.getElementById('startBtn').disabled = true;
                    document.getElementById('stopBtn').disabled = true;
                    
                    // 清理音频资源
                    if (mediaStream) {
                        mediaStream.getTracks().forEach(track => track.stop());
                        mediaStream = null;
                    }
                    if (audioContext) {
                        audioContext.close();
                        audioContext = null;
                    }
                };

                ws.onerror = function(error) {
                    addLog(`WebSocket错误: ${error}`, 'error');
                    updateStatus('disconnected', '连接失败');
                    
                    // 如果是file://协议，给出特殊提示
                    if (window.location.protocol === 'file:') {
                        addLog('检测到file://协议，请通过HTTP服务器访问此页面', 'error');
                        addLog('正确的访问地址: http://localhost:8000/static-pages/aliyun_asr_test.html', 'info');
                    }
                };

            } catch (error) {
                addLog(`连接失败: ${error.message}`, 'error');
                updateStatus('disconnected', '连接失败');
                
                // 如果是file://协议，给出特殊提示
                if (window.location.protocol === 'file:') {
                    addLog('检测到file://协议，请通过HTTP服务器访问此页面', 'error');
                    addLog('正确的访问地址: http://localhost:8000/static-pages/aliyun_asr_test.html', 'info');
                }
            }
        }

        // 断开连接
        function disconnect() {
            if (ws) {
                ws.close();
            }
        }

        // 处理WebSocket消息
        function handleMessage(data) {
            switch (data.type) {
                case 'started':
                    addLog('识别已开始', 'success');
                    break;
                case 'result':
                    addLog(`识别结果: ${data.text} | 句子结束: ${data.sentence_end ? '是' : '否'}`, 'success');
                    document.getElementById('resultContainer').innerHTML = 
                        `<div class="result-text">
                            <span>${data.text}</span>
                            <br>
                            <span style="color:#1890ff;font-weight:bold;">是否句子结束：${data.sentence_end ? '是' : '否'}</span>
                        </div>`;
                    break;
                case 'stopped':
                    addLog('识别已停止', 'info');
                    break;
                case 'error':
                    addLog(`错误: ${data.message}`, 'error');
                    break;
                case 'pong':
                    addLog('收到心跳响应', 'info');
                    break;
                default:
                    addLog(`收到未知消息: ${JSON.stringify(data)}`, 'warning');
            }
        }

        // 开始识别
        async function startRecognition() {
            if (!isConnected || isRecognizing) return;

            try {
                addLog('正在启动语音识别...', 'info');

                // 获取配置
                const config = {
                    model: document.getElementById('model').value,
                    format: document.getElementById('format').value,
                    sample_rate: parseInt(document.getElementById('sampleRate').value),
                    language_hints: document.getElementById('languageHints').value.split(',').map(s => s.trim())
                };

                // 发送开始命令
                ws.send(JSON.stringify({
                    type: 'start',
                    config: config
                }));

                // 请求麦克风权限
                mediaStream = await navigator.mediaDevices.getUserMedia({ 
                    audio: {
                        sampleRate: config.sample_rate,
                        channelCount: 1,
                        echoCancellation: true,
                        noiseSuppression: true
                    } 
                });

                // 创建音频上下文
                audioContext = new AudioContext({ sampleRate: config.sample_rate });
                const source = audioContext.createMediaStreamSource(mediaStream);
                const processor = audioContext.createScriptProcessor(4096, 1, 1);

                processor.onaudioprocess = function(e) {
                    if (isRecognizing && ws && ws.readyState === WebSocket.OPEN) {
                        const inputData = e.inputBuffer.getChannelData(0);
                        
                        // 转换为16位PCM
                        const pcmData = new Int16Array(inputData.length);
                        for (let i = 0; i < inputData.length; i++) {
                            pcmData[i] = Math.max(-32768, Math.min(32767, inputData[i] * 32768));
                        }
                        
                        // 发送音频数据
                        const base64Data = btoa(String.fromCharCode(...new Uint8Array(pcmData.buffer)));
                        ws.send(JSON.stringify({
                            type: 'audio',
                            data: base64Data
                        }));
                        
                        audioChunks++;
                        document.getElementById('audioChunks').textContent = audioChunks;
                    }
                };

                source.connect(processor);
                processor.connect(audioContext.destination);

                isRecognizing = true;
                document.getElementById('startBtn').disabled = true;
                document.getElementById('stopBtn').disabled = false;
                
                addLog('语音识别已开始，请说话...', 'success');

            } catch (error) {
                addLog(`启动识别失败: ${error.message}`, 'error');
            }
        }

        // 停止识别
        function stopRecognition() {
            if (!isRecognizing) return;

            try {
                // 发送停止命令
                if (ws && ws.readyState === WebSocket.OPEN) {
                    ws.send(JSON.stringify({ type: 'stop' }));
                }

                // 停止音频流
                if (mediaStream) {
                    mediaStream.getTracks().forEach(track => track.stop());
                    mediaStream = null;
                }

                if (audioContext) {
                    audioContext.close();
                    audioContext = null;
                }

                isRecognizing = false;
                document.getElementById('startBtn').disabled = false;
                document.getElementById('stopBtn').disabled = true;
                
                addLog('语音识别已停止', 'info');

            } catch (error) {
                addLog(`停止识别失败: ${error.message}`, 'error');
            }
        }

        // 清空结果
        function clearResults() {
            document.getElementById('resultContainer').innerHTML = 
                '<div class="result-text">等待开始识别...</div>';
            document.getElementById('logContainer').innerHTML = '';
            audioChunks = 0;
            document.getElementById('audioChunks').textContent = '0';
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            addLog('阿里云ASR测试页面已加载', 'info');
            
            // 检测访问方式
            if (window.location.protocol === 'file:') {
                addLog('⚠️ 检测到file://协议访问', 'warning');
                addLog('请通过HTTP服务器访问此页面以获得最佳体验', 'warning');
                addLog('正确地址: http://localhost:8000/static-pages/aliyun_asr_test.html', 'info');
            } else {
                addLog('✅ 通过HTTP服务器访问，连接正常', 'success');
            }
            
            // 显示当前WebSocket URL
            const wsUrl = getWebSocketUrl();
            addLog(`WebSocket连接地址: ${wsUrl}`, 'info');
            
            // 自动连接（可选）
            // setTimeout(connect, 1000);
        });

        // 页面卸载时清理资源
        window.addEventListener('beforeunload', function() {
            if (ws) {
                ws.close();
            }
            if (mediaStream) {
                mediaStream.getTracks().forEach(track => track.stop());
            }
            if (audioContext) {
                audioContext.close();
            }
        });
    </script>
</body>
</html> 